leetcode 859 problem solution in python